package com.scrapy.http.html;

import com.scrapy.http.pojo.Reply;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 分析出评论者的类
 * Created by wanter on 2016/11/10.
 */
public class AnalysisReplyHtml {
    /**
     * 页面上的内容
     */
    private String htmlContent;
    /**
     * 页面上评论区的内容
     */
    private List<Reply> replyList;

    public AnalysisReplyHtml(String htmlContent) {
        this.htmlContent = htmlContent;
    }


    private String getReplyContent(){
        String regex = "comments-wrap.*?<div class=\"report\">1</div>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(this.htmlContent);
        if (matcher.find()){
            return matcher.group();
        }
        return "获取评论区失败";
    }

    public List<Reply> getReplyList(){
        replyList = new ArrayList<>();
        String str = this.getReplyContent();
        String[] strings = str.split("comment-block clearfix");
        Reply reply = null;
        for (int i = 1; i < strings.length; i++) {
            String temp = strings[i];
            /**
             * 评论的内容
             */
            reply = new Reply();
            String replyRgex = "<span class=\"body\">(.*?)</span>";
            String userUrlRegex = "<a href=\"(.*?)\" target=\"_blank\" rel=\"nofollow\">";


            reply.setMesg(getMatcherByRegex(temp, replyRgex));
            reply.setReplyUserUrl("http://www.qiushibaike.com"+getMatcherByRegex(temp,userUrlRegex));
            reply.setDate(new Date());
            reply.setFooter(Integer.parseInt(this.getFlooter(temp)));
            replyList.add(reply);
        }
        return replyList;

    }

    private String getMatcherByRegex(String temp, String replyRgex) {
        Pattern pattern = Pattern.compile(replyRgex);
        Matcher matcher = pattern.matcher(temp);
        if (matcher.find()){
            return matcher.group(1);
        }
        return "分析失败";
    }

    /**
     * 拿到楼层的数
     * @param temp 传入的字符串
     * @return 返回楼层数
     */
    private String getFlooter(String temp){
        String[] splits = temp.split("\"report\">");
        String str[] = splits[1].split("</div>");
        return str[0];
    }

}
